package ac.github.os.internal.core.skill

import ac.github.os.OriginSkill
import ac.github.os.api.OriginSkillAPI
import ac.github.os.internal.core.action.Action
import ac.github.os.internal.core.objective.EntityObjective
import ac.github.os.internal.core.objective.LocationObjective
import ac.github.os.internal.session.Cache
import ac.github.os.internal.session.Session
import ac.github.os.util.serialize

class Skill(
    val string: String
) {

    fun cast(session: Session) {
        val serialize = string.serialize()
        val list = serialize.split(" ").toMutableList()

        val cache = Cache()

        list.filter { it[0] == '@' }.forEach {
            OriginSkillAPI.check(it).apply {
                val substring = key.substring(1)
                value.initial(session)

                OriginSkill.selectors.firstOrNull { it.namespace == substring }?.doSelect(session, value)?.forEach {
                    cache.objectives.add(it)
                }
            }
        }

        list.filter { it[0] == '~' }.forEach {
            OriginSkillAPI.check(it).apply {
                val substring = key.substring(1)
                value.initial(session)
                OriginSkill.selectors.firstOrNull { it.namespace == substring }?.doSelect(session, value)?.forEach {
                    cache.objectives.removeIf { o -> o.keyId() == it.keyId() }
                }
            }
        }

        list.filter { it[0] != '@' }.forEach {
            OriginSkillAPI.check(it).apply {
                value.initial(session)
                OriginSkill.actions.firstOrNull { it.namespace == key }?.apply {

                    when (type) {
                        Action.Type.ENTITY -> {
                            cache.objectives.removeIf { it !is EntityObjective }
                            if (cache.objectives.isEmpty()) return
                        }
                        Action.Type.LOCATION -> {
                            cache.objectives.removeIf { it !is LocationObjective }
                            if (cache.objectives.isEmpty()) return
                        }
                        Action.Type.AIR -> {
                        }
                    }

                    onExecute(session, cache, value)
                }
            }
        }

    }


}